import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86186
 * Date: 2023-08-26
 * Time: 12:27
 */
public class Test {
    //leetcode 560 和为k的子数组
    public int subarraySum(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<>();
        //防止整个数组的和为k，然后就是需要在[0,-1]这个区间找前缀和为sum[i] - k的值，但是这个区间是不合法的
        map.put(0,1);
        int sum = 0,ret = 0;
        for(int i = 0; i < nums.length; i++) {
            sum += nums[i];
            ret += map.getOrDefault(sum-k,0);
            map.put(sum,map.getOrDefault(sum,0) + 1);
        }

        return ret;
    }

    //leetcode 974 和可被k整除的子数组
    public int subarraysDivByK(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<>();
        map.put(0 % k,1);
        int sum = 0,ret = 0;
        for(int i = 0; i < nums.length; i++) {
            sum += nums[i];
            int r = (sum % k + k) % k;
            ret += map.getOrDefault(r,0);
            map.put(r,map.getOrDefault(r,0) + 1);
        }

        return ret;
    }

    //leetcode 525 最长连续数组
    public int findMaxLength(int[] nums) {
        Map<Integer,Integer> map = new HashMap<>();
        map.put(0,-1);  //哈希表中存放子数组的和以及下标
        int sum = 0,ret = 0;
        for(int i = 0; i < nums.length; i++) {
            sum += (nums[i] == 0 ? -1 : 1);
            if(map.containsKey(sum)) ret = Math.max(ret,i-map.getOrDefault(sum,0));
            else map.put(sum,i);
        }

        return ret;
    }

    public int[][] matrixBlockSum(int[][] mat, int k) {
        int m = mat.length;
        int n = mat[0].length;
        int[][] dp = new int[m + 1][n + 1];
        for(int i = 1; i <= m; i++) {
            for(int j = 1; j <= n; j++) {
                dp[i][j] = dp[i-1][j] + dp[i][j -1] + mat[i - 1][j - 1] - dp[i - 1][j - 1];
            }
        }

        //leetcode 1314 矩阵区域和
        int[][] ret = new int[m][n];
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                int x1 = Math.max(0,i-k) + 1,y1 = Math.max(0,j-k) + 1;
                int x2 = Math.min(m-1,i+k) + 1,y2 = Math.min(n-1,j+k) + 1;
                ret[i][j] = dp[x2][y2] - dp[x1-1][y2] - dp[x2][y1-1] + dp[x1-1][y1-1];
            }
        }

        return ret;
    }
}
